package com.crack.nga2.activity;

import android.app.Application;
import android.app.Service;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.crack.nga2.span.BitmapCache;
import com.crack.nga2.span.DiskLruCache;
import com.crack.nga2.utils.GlobalConst;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义进程类
 * Created by Administrator on 2016/1/11.
 */
public class NgaApplication extends Application {
    private static RequestQueue mQueue;
    private static ImageLoader imageLoader;
    private static RequestQueue imageQueue;
    public static DiskLruCache diskLruCache;
    public LocationClient locationClient = null;
    public BDLocationListener locationListener = null;
    public TextView mLocationResult, logMsg;
    public TextView trigger, exit;
    public Vibrator mVibrator;
    /**
     * 疼迅分享
     */
    public static Tencent mTencent;
    public static IWXAPI mIwxApi;

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化表情映射表
        initEmotions();

        initVolleyAndCacheConfig();

        readLoginCookie();
        initLocate();
        mTencent = Tencent.createInstance("1105039459", getApplicationContext());
        mIwxApi = WXAPIFactory.createWXAPI(getApplicationContext(), GlobalConst.WEIXIN_APP_ID);
    }

    private void readLoginCookie() {
        File file = new File(getFilesDir(), "cookie.cache");
        if (file.exists()) {
            try {
                FileReader reader = new FileReader(file);
                BufferedReader bufferedReader = new BufferedReader(reader);
                GlobalConst.Cookie = bufferedReader.readLine();
                GlobalConst.NO_LOGIN_COOKIE = GlobalConst.Cookie;
                bufferedReader.close();
                GlobalConst.isLogin = true;
                //获取uid
                Pattern p = Pattern.compile("(?<=ngaPassportUid=)(\\d+?)(?=;)");
                Matcher m = p.matcher(GlobalConst.Cookie);
                if (m.find()) {
                    GlobalConst.UID = Integer.parseInt(m.group());
                }
                //获取用户名
                p = Pattern.compile("(?<=ngaPassportUrlencodedUname=)(.+?)(?=;)");
                m = p.matcher(GlobalConst.Cookie);
                if (m.find()) {
                    GlobalConst.username = URLDecoder.decode(URLDecoder.decode(m.group(), "GBK"), "GBK");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化缓存和Volley配置
     */
    private void initVolleyAndCacheConfig() {
        Class<?> clazz = DefaultRetryPolicy.class;
        Class<?> requestClazz = RequestQueue.class;
        try {
            //设置连接超时
            Field field = clazz.getField("DEFAULT_TIMEOUT_MS");
            field.setAccessible(true);
            field.set(null, 25000);
            //设置线程数量
            field = requestClazz.getDeclaredField("DEFAULT_NETWORK_THREAD_POOL_SIZE");
            field.setAccessible(true);
            field.set(null, 2);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        try {
            File cacheFile = new File(getExternalCacheDir(), "bitmap");
            if (!cacheFile.exists()) {
                boolean b = cacheFile.mkdirs();
                Log.i("tag", "缓存：" + b);
            }
            diskLruCache = DiskLruCache.open(cacheFile, 1, 1, 150 * 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取应用程序的最大内存
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        //用最大内存的1/4来存储图片
        BitmapCache.MAX_SIZE = maxMemory / 4;
        mQueue = Volley.newRequestQueue(getApplicationContext());
        imageLoader = new ImageLoader(imageQueue = Volley.newRequestQueue(getApplicationContext()), BitmapCache.getInstance());
    }

    public static void cancelAllVolleyRequest() {
        mQueue.cancelAll(new RequestQueue.RequestFilter() {
            @Override
            public boolean apply(Request<?> request) {
                return true;
            }
        });
        imageQueue.cancelAll(new RequestQueue.RequestFilter() {
            @Override
            public boolean apply(Request<?> request) {
                return true;
            }
        });
    }

    private void initLocate() {
        //初始化定位功能
        locationClient = new LocationClient(getApplicationContext());
        locationListener = new MyLocationListener();
        locationClient.registerLocationListener(locationListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setAddrType("all");//返回的定位结果包含地址信息
        option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
        option.disableCache(true);//禁止启用缓存定位
        locationClient.setLocOption(option);
        mVibrator = (Vibrator) getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        locationClient.start();
    }

    public static RequestQueue getQueue() {
        return mQueue;
    }

    public static ImageLoader getImageLoader() {
        return imageLoader;
    }

    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                GlobalConst.ADDR = location.getAddrStr();
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                GlobalConst.ADDR = location.getAddrStr();
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");// 位置语义化信息
            sb.append(location.getLocationDescribe());
            List<Poi> list = location.getPoiList();// POI信息
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId()).append(" ").append(p.getName()).append(" ").append(p.getRank());
                }
            }
            logMsg(sb.toString());
            Log.i("BaiduLocationApiDem", sb.toString());
            locationClient.stop();
        }


    }

    public void logMsg(String str) {
        try {
            if (mLocationResult != null)
                mLocationResult.setText(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initEmotions() {
        Map<String, String> emotions = GlobalConst.emotions;
        emotions.put("ac:blink", "[s:ac:blink]");
        emotions.put("ac:cahan", "[s:ac:擦汗]");
        emotions.put("ac:cha", "[s:ac:茶]");
        emotions.put("ac:chaoxiao", "[s:ac:嘲笑]");
        emotions.put("ac:chaoxiao1", "[s:ac:嘲笑1]");
        emotions.put("ac:chou", "[s:ac:愁]");
        emotions.put("ac:chuan", "[s:ac:喘]");
        emotions.put("ac:dai", "[s:ac:呆]");
        emotions.put("ac:e", "[s:ac:哦]");
        emotions.put("ac:fangdui", "[s:ac:反对]");
        emotions.put("ac:goodjob", "[s:ac:goodjob]");
        emotions.put("ac:han", "[s:ac:汗]");
        emotions.put("ac:heiqiang", "[s:ac:黑枪]");
        emotions.put("ac:heng", "[s:ac:哼]");
        emotions.put("ac:huachi", "[s:ac:花痴]");
        emotions.put("ac:jihuatong", "[s:ac:计划通]");
        emotions.put("ac:jing", "[s:ac:惊]");
        emotions.put("ac:jiong", "[s:ac:囧]");
        emotions.put("ac:koubi", "[s:ac:抠鼻]");
        emotions.put("ac:ku", "[s:ac:酷]");
        emotions.put("ac:ku1", "[s:ac:酷1]");
        emotions.put("ac:kuxiao", "[s:ac:哭笑]");
        emotions.put("ac:leng", "[s:ac:冷]");
        emotions.put("ac:lingluan", "[s:ac:凌乱]");
        emotions.put("ac:o", "[s:ac:哦]");
        emotions.put("ac:pa", "[s:ac:怕]");
        emotions.put("ac:pen", "[s:ac:喷]");
        emotions.put("ac:shang", "[s:ac:上]");
        emotions.put("ac:shanguang", "[s:ac:闪光]");
        emotions.put("ac:shuai", "[s:ac:摔]");
        emotions.put("ac:touxiao", "[s:ac:偷笑]");
        emotions.put("ac:weiqu", "[s:ac:委屈]");
        emotions.put("ac:wen", "[s:ac:问]");
        emotions.put("ac:wuyu", "[s:ac:无语]");
        emotions.put("ac:xia", "[s:ac:吓]");
        emotions.put("ac:xianmu", "[s:ac:羡慕]");
        emotions.put("ac:xiaren", "吓人");
        emotions.put("ac:xiu", "[s:ac:羞]");
        emotions.put("ac:yi", "[s:ac:咦]");
        emotions.put("ac:youshang", "[s:ac:忧伤]");
        emotions.put("ac:yun", "[s:ac:晕]");
        emotions.put("ac:zantong", "[s:ac:赞同]");
        emotions.put("ac:zhongqiang", "[s:ac:中枪]");
        emotions.put("ac:zhuakuang", "[s:ac:抓狂]");
        /* ========================= */
        emotions.put("dt:aojiao", "[s:dt:傲娇]");
        emotions.put("dt:bishi", "[s:dt:鄙视]");
        emotions.put("dt:chaoxiao", "[s:dt:嘲笑]");
        emotions.put("dt:chachuqu", "[s:dt:叉出去]");
        emotions.put("dt:faguang", "[s:dt:发光]");
        emotions.put("dt:haqian", "[s:dt:呵欠]");
        emotions.put("dt:heilian", "[s:dt:黑脸]");
        emotions.put("dt:jing", "[s:dt:惊]");
        emotions.put("dt:jing2", "[s:dt:惊2]");
        emotions.put("dt:kengutou", "[s:dt:啃骨头]");
        emotions.put("dt:ku", "[s:dt:哭]");
        emotions.put("dt:lei", "[s:dt:雷]");
        emotions.put("dt:lei2", "[s:dt:雷2]");
        emotions.put("dt:lianhong", "[s:dt:脸红]");
        emotions.put("dt:nu", "[s:dt:怒]");
        emotions.put("dt:nu2", "[s:dt:怒2]");
        emotions.put("dt:ROLL", "[s:dt:ROLL]");
        emotions.put("dt:shang", "[s:dt:上]");
        emotions.put("dt:shao", "[s:dt:烧]");
        emotions.put("dt:shuai", "[s:dt:摔]");
        emotions.put("dt:wuyu", "[s:dt:无语]");
        emotions.put("dt:xian", "[s:dt:闲]");
        emotions.put("dt:xiao", "[s:dt:笑]");
        emotions.put("dt:xiao2", "[s:dt:笑2]");
        emotions.put("dt:xiao3", "[s:dt:笑3]");
        emotions.put("dt:xin", "[s:dt:心]");
        emotions.put("dt:xingxingyan", "[s:dt:星星眼]");
        emotions.put("dt:xingxingyan2", "[s:dt:星星眼2]");
        emotions.put("dt:yao", "[s:dt:药]");
        emotions.put("dt:yuan", "[s:dt:怨]");
        emotions.put("dt:yun", "[s:dt:晕]");
        emotions.put("dt:zhuyi", "[s:dt:注意]");
        emotions.put("dt:zhuyi2", "[s:dt:注意2]");
         /* ========================= */
        emotions.put("pst:anwei", "[s:pst:安慰]");
        emotions.put("pst:bei", "[s:pst:背]");
        emotions.put("pst:bixue", "[s:pst:鼻血]");
        emotions.put("pst:can", "[s:pst:惨]");
        emotions.put("pst:chaoxiao", "[s:pst:嘲笑]");
        emotions.put("pst:dai", "[s:pst:呆]");
        emotions.put("pst:dai2", "[s:pst:呆2]");
        emotions.put("pst:dai3", "[s:pst:呆3]");
        emotions.put("pst:dianji", "[s:pst:电击]");
        emotions.put("pst:faguang", "[s:pst:发光]");
        emotions.put("pst:fu", "[s:pst:扶]");
        emotions.put("pst:haqian", "[s:pst:呵欠]");
        emotions.put("pst:heilian", "[s:pst:黑脸]");
        emotions.put("pst:huaiyi", "[s:pst:怀疑]");
        emotions.put("pst:huoxing", "[s:pst:火星]");
        emotions.put("pst:ji", "[s:pst:基]");
        emotions.put("pst:jingdai", "[s:pst:惊呆]");
        emotions.put("pst:jingdai2", "[s:pst:惊呆2]");
        emotions.put("pst:jingdai3", "[s:pst:惊呆3]");
        emotions.put("pst:jingxia", "[s:pst:惊吓]");
        emotions.put("pst:jingxia2", "[s:pst:惊吓2]");
        emotions.put("pst:jinzhang", "[s:pst:紧张]");
        emotions.put("pst:jushou", "[s:pst:举手]");
        emotions.put("pst:kaixin", "[s:pst:开心]");
        emotions.put("pst:kaixin2", "[s:pst:开心2]");
        emotions.put("pst:kaixin3", "[s:pst:开心3]");
        emotions.put("pst:kanxi", "[s:pst:看戏]");
        emotions.put("pst:ku", "[s:pst:哭]");
        emotions.put("pst:ku2", "[s:pst:哭2]");
        emotions.put("pst:ku3", "[s:pst:哭3]");
        emotions.put("pst:lei", "[s:pst:泪]");
        emotions.put("pst:lei2", "[s:pst:泪2]");
        emotions.put("pst:lei3", "[s:pst:泪3]");
        emotions.put("pst:lei4", "[s:pst:泪4]");
        emotions.put("pst:lianhong", "[s:pst:脸红]");
        emotions.put("pst:lianhong2", "[s:pst:脸红2]");
        emotions.put("pst:manzu", "[s:pst:满足]");
        emotions.put("pst:manzu2", "[s:pst:满足2]");
        emotions.put("pst:meiwei", "[s:pst:美味]");
        emotions.put("pst:men", "[s:pst:闷]");
        emotions.put("pst:men2", "[s:pst:闷2]");
        emotions.put("pst:nu", "[s:pst:怒]");
        emotions.put("pst:nu2", "[s:pst:怒2]");
        emotions.put("pst:ou", "[s:pst:呕]");
        emotions.put("pst:qin", "[s:pst:亲]");
        emotions.put("pst:shayan", "[s:pst:傻眼]");
        emotions.put("pst:shayan2", "[s:pst:傻眼2]");
        emotions.put("pst:touxiao", "[s:pst:偷笑]");
        emotions.put("pst:touxiao2", "[s:pst:偷笑2]");
        emotions.put("pst:touxiao3", "[s:pst:偷笑3]");
        emotions.put("pst:tuzi", "[s:pst:兔子]");
        emotions.put("pst:xiaoerbuyu", "[s:pst:笑而不语]");
        emotions.put("pst:xie", "[s:pst:谢]");
        emotions.put("pst:xieyan", "[s:pst:斜眼]");
        emotions.put("pst:xingfu", "[s:pst:幸福]");
        emotions.put("pst:xingxingyan", "[s:pst:星星眼]");
        emotions.put("pst:yandai", "[s:pst:眼袋]");
        emotions.put("pst:yanjing", "[s:pst:眼镜]");
        emotions.put("pst:yateng", "[s:pst:牙疼]");
        emotions.put("pst:yinyue", "[s:pst:音乐]");
        emotions.put("pst:yuan", "[s:pst:怨]");
        emotions.put("pst:yun", "[s:pst:晕]");
        emotions.put("pst:zhai", "[s:pst:宅]");
        emotions.put("pst:zui", "[s:pst:醉]");
    }

}